package com.labichaoka.chaoka.ui.bank.bind;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.labichaoka.chaoka.BuildConfig;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.base.GlobalParams;
import com.labichaoka.chaoka.entity.BankInfoDtoResponse;
import com.labichaoka.chaoka.entity.BaseResponse;
import com.labichaoka.chaoka.entity.BindBankRequest;
import com.labichaoka.chaoka.entity.GetBankSmsRequest;
import com.labichaoka.chaoka.entity.IDCardResponse;
import com.labichaoka.chaoka.entity.SwitchCardResponse;
import com.labichaoka.chaoka.ui.baseinfo.information.InformationAuthenticationActivity;
import com.labichaoka.chaoka.ui.web.WebViewActivity;
import com.labichaoka.chaoka.utils.DetectionUtil;
import com.labichaoka.chaoka.utils.SMSManager;
import com.labichaoka.chaoka.utils.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

public class BankBindActivity extends BaseActivity implements BankBindView {
    @BindView(R.id.next1)
    TextView next;
    @BindView(R.id.tv_title)
    TextView title;

    @BindView(R.id.username)
    TextView uname;
    @BindView(R.id.bank_num)
    TextView bank_num;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.bank_type)
    TextView bank_type;
    @BindView(R.id.commit)
    Button commit;
    @BindView(R.id.recycleView)
    RecyclerView recyclerV;

    private String phoneStr;
    private String banTypeStr;
    private String banNumStr;

    private BankBindPresenter presenter;
    private Dialog dialog;
    private BankInfoDtoResponse bankTypeList;
    private int type;//1代表绑卡2代表换卡

    @Override
    protected int initLayoutId() {
        return R.layout.activity_bank_bind;
    }

    @Override
    protected void initView() {
        next.setTypeface(iconfont);
    }

    @Override
    protected void initData() {
        presenter=new BankBindPresenterImpl(this,new BankBindInteractorImpl());
        presenter.getIDCardName();
        presenter.getBankCardList();
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type=getIntent().getExtras().getInt("type",0);
        if (type==0){
            return;
        }
        if (type==GlobalParams.BIND_BANK_CARD){
            title.setText("绑定银行卡");
        }else if(type==GlobalParams.CHANGE_BANK_CARD){
            title.setText("更换银行卡");
        }

        bank_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                banNumStr=s.toString().trim();
                checkBtnState();
            }
        });

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                phoneStr=s.toString().trim();
                checkBtnState();
            }
        });
    }

    @OnClick({R.id.commit,R.id.bank_type_layout})
    public void click(View v){
        switch (v.getId()){
            case R.id.commit:
                if (!DetectionUtil.isMobileNO(phoneStr)){
                    ToastUtils.show("请输入正确的手机号!");
                    return;
                }
                //提交
                GetBankSmsRequest request=new GetBankSmsRequest();
                request.setBankTypeCode(banTypeStr);
                request.setBankPhone(phoneStr);
                request.setBankNo(banNumStr);
                request.setCallBackUrl(BuildConfig.WEB_HOST+"blankPage");
                if (type==GlobalParams.BIND_BANK_CARD){
                    presenter.bindCard(request);
                }else{
                    presenter.scrdSwitchCard(request);
                }

                presenter.behavior(GlobalParams.SUB_BANKCARD_INFO);

                break;
            case R.id.bank_type_layout:
                showBankTypeDialog();
                break;
        }
    }

    @Override
    public void showProgress() {
        showLoadingProgress();
    }

    @Override
    public void hideProgress() {
        hideLoadingProgress();
    }

    @Override
    public void getIDNameCallback(IDCardResponse response) {
        String name=response.getData().getRealName();
        if(!TextUtils.isEmpty(name)){
            name="**"+name.substring(name.length()-1,name.length());
        }
        uname.setText(name);
    }

    public void showVerifyCodeDialog() {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.verify_code_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.showdialog);
        TextView close_icon = v.findViewById(R.id.close);
        TextView code_btn = v.findViewById(R.id.code_btn);
        TextView notice = v.findViewById(R.id.notice);
        Button submit = v.findViewById(R.id.submit);
        EditText edit_code= v.findViewById(R.id.edit_code);
        String phone = phoneStr.substring(0, 3) + "****" + phoneStr.substring(7, 11);
        notice.setText("验证码已发送至您"+phone+"的手机号，请输入验证码以完成还款验证：");

        SMSManager.getInstance(mContext).bindView(code_btn);

        close_icon.setTypeface(iconfont);
        close_icon.setOnClickListener((view) -> {
            dialog.dismiss();
        });
        code_btn.setOnClickListener(v1 -> {
            GetBankSmsRequest request=new GetBankSmsRequest();
            request.setBankTypeCode(banTypeStr);
            request.setBankPhone(phoneStr);
            request.setBankNo(banNumStr);
            presenter.getSMSCode(request);
        });
        submit.setOnClickListener(v12 -> {
            BindBankRequest request=new BindBankRequest();
            request.setBankTypeCode(banTypeStr);
            request.setBankPhone(phoneStr);
            request.setBankNo(banNumStr);
            request.setVerfiyCode(edit_code.getText().toString());
            request.setCallBackUrl(BuildConfig.WEB_HOST+"blankPage");


            if (type==GlobalParams.BIND_BANK_CARD){
                presenter.bindCardVail(request);
            }else{
                presenter.submitSwitchCard(request);
            }

        });
        edit_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length()>0){
                    submit.setEnabled(true);
                }else{
                    submit.setEnabled(false);
                }
            }
        });


        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();

    }


    public void showBankTypeDialog() {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_bank_type, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.showdialog);
        TextView close_icon =  v.findViewById(R.id.close);
        RecyclerView recyclerView =  v.findViewById(R.id.rv_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this,R.drawable.divide_drawable));
        recyclerView.addItemDecoration(divider);

        close_icon.setTypeface(iconfont);
        close_icon.setOnClickListener((view) -> {
            dialog.dismiss();
        });

        if (bankTypeList==null){
            return;
        }
        BankTypeAdapter adapter = new BankTypeAdapter(mContext, bankTypeList.getData());
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener((position -> {
            dialog.dismiss();
            bank_type.setText(bankTypeList.getData().get(position).getShortName());
            bank_type.setTextColor(getResources().getColor(R.color.font_3a3a38));
            banTypeStr=bankTypeList.getData().get(position).getCode();
        }));

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();

    }


    @Override
    public void startCountDown() {
        SMSManager.getInstance(mContext).start();
    }

    @Override
    public void countDownCancel() {
        SMSManager.getInstance(mContext).cancel();
    }

    @Override
    public void getBankTypeCallBack(BankInfoDtoResponse response) {
        if (response==null){
            ToastUtils.show("获取银行卡列表数据异常!");
            return;
        }
        bankTypeList=response;

        recyclerV.setLayoutManager(new GridLayoutManager(this,3));
        BankListAdapter adapter = new BankListAdapter(mContext, bankTypeList.getData());
        recyclerV.setAdapter(adapter);
    }

    @Override
    public void submitBankCardInfo(BaseResponse response) {
        if (response!=null){
            if (response.getCode().equals("1")){
                gotoActivity(mContext,InformationAuthenticationActivity.class,null);
                finish();
            }else if (response.getCode().equals("200")){
                startCountDown();
                showVerifyCodeDialog();
            }else if(response.getCode().equals("204")){
                ToastUtils.show(response.getMessage());
            }
        }
    }

    @Override
    public void bindCardVail(BaseResponse response) {
        gotoActivity(mContext,InformationAuthenticationActivity.class,null);
        finish();
    }

    @Override
    public void scrdSwitchCardCallback(SwitchCardResponse response) {
        if (response!=null){
            if (response.getCode().equals("1")){
                String cardFlag=response.getData().getCardFlag();
                if (TextUtils.isEmpty(cardFlag)){
                    ToastUtils.show("获取数据异常，请稍候重试！");
                    return;
                }
                if (!cardFlag.equals("1")){
                    String url=response.getData().getOpenUrl();
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "9");
                    bundle.putString("url", url);
                    gotoActivity(mContext, WebViewActivity.class, bundle);
                }
                finish();
            }else if (response.getCode().equals("200")){
                startCountDown();
                showVerifyCodeDialog();
            }else if(response.getCode().equals("204")){
                ToastUtils.show(response.getMessage());
            }
        }
    }

    @Override
    public void submitSwitchCardCallback(SwitchCardResponse response) {
        if (response.getData()==null){
            return;
        }
        String cardFlag=response.getData().getCardFlag();
        if (TextUtils.isEmpty(cardFlag)){
            ToastUtils.show("获取数据异常，请稍候重试！");
            return;
        }
        if (!cardFlag.equals("1")){
            String url=response.getData().getOpenUrl();
            Bundle bundle = new Bundle();
            bundle.putString("type", "9");
            bundle.putString("url", url);
            gotoActivity(mContext, WebViewActivity.class, bundle);
        }
        finish();
    }


    public void checkBtnState(){
        if (!TextUtils.isEmpty(phoneStr)&&!TextUtils.isEmpty(banTypeStr)&&!TextUtils.isEmpty(banNumStr)){
            commit.setEnabled(true);
        }else{
            commit.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }
}
